<?php

namespace Caifenglei\AuthRbac\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Auth\Access\Response as AuthResponse;
use Illuminate\Auth\Middleware\Authorize as AuthorizeMiddleware;

class Authorize
{

    /**
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        if(config('auth-rbac.api_auth_enabled')) {
            $user = $request->user();
            if($user){
                $route_name = $request->route()->getName();
                if($route_name){
                    if(!in_array($route_name, config('auth-rbac.authorized_free_routes', [])) && !$request->user()->can($route_name)){
                        return response()->json([
                            'code' => 403,
                            'msg' => '抱歉，没有权限: '.$route_name,
                            'time' => time()
                        ]);
                    }
                }
            }
        }
        return $next($request);
    }
}
